<script setup>
import api from '../../api/admin_api.js'
import {ref, onMounted, onUnmounted} from "vue";
import {ElMessageBox} from "element-plus";
import lodash from 'lodash'

//定义绑定的数据
//表格中的数据
const tableData = ref([]);
const total = ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);
const addWinVisible = ref(false);

//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  id: '',
  username: '',
  password: '',
  email: '',
  phone: '',
  avatar: '',
  role: '管理员', // 只展示管理员角色
  status: '',
  create_time: '',
  update_time: '',
  is_del: '',
});

//要修改或者新增的数据
const obj = ref({});
const search = async () => {
  try {
    // 确保角色过滤条件始终存在
    if (!searchObj.value.role) {
      searchObj.value.role = '管理员';
    }
    console.log('发送的查询参数:', searchObj.value);

    var result = await api.getAdminPage(searchObj.value.current, searchObj.value.limit, searchObj.value);
    console.log('收到的响应数据:', result);

    // 按照 userList.vue 的方式处理分页数据
    tableData.value = result.records;
    total.value = result.total;
  } catch (error) {
    console.error('获取管理员列表时出错:', error);
    tableData.value = [];
    total.value = 0;
  }
}

// 处理用户信息更新事件
const handleUserInfoUpdated = () => {
  // 延迟一段时间后重新加载数据，确保数据库已更新
  setTimeout(() => {
    search();
  }, 500);
}

//页面加载后要挂载的数据
onMounted(async () => {
  await search();
  // 监听用户信息更新事件
  window.addEventListener('user-info-updated', handleUserInfoUpdated);
});

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('user-info-updated', handleUserInfoUpdated);
});

//重置查询条件
const resetSearch = () => {
  searchObj.value.username = '';
  searchObj.value.phone = '';
  searchObj.value.current = 1;
  search();
}

//上传成功
const handleUploadSuccess = (response, file) => {
  console.log("-----------------");
  console.log(response);
  console.log(file);
  obj.value.avatar = response.data;
}

//分页查询用
const handleSizeChange = () => {
  search();
}

//分页查询用
const handleCurrentChange = () => {
  search();
}

//定义方法
const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
}

const handlerAdd = () => {//添加
  obj.value = {
    role: '管理员' // 显式设置角色为管理员
  };
  addWinVisible.value = true;//打开对话框
}

//新增对话框的取消按钮点击事件
const addCancel = () => {
  obj.value = {};//清空数据
  addWinVisible.value = false;//关闭新增对话框
}

//编辑对话框的取消按钮点击事件
const editCancel = () => {
  obj.value = {};//清空数据
  editWinVisible.value = false;//关闭对话框
}

//编辑对话框的提交按钮点击事件
const editCommit = async () => {
  await api.updateAdmin(obj.value);//提交修改数据
  await search();//刷新表格
  editWinVisible.value = false;//关闭编辑对话框

  // 发送全局事件通知其他组件刷新数据
  window.dispatchEvent(new CustomEvent('user-info-updated'));
}

//新增对话框的提交按钮点击事件
const addCommit = async () => {
  await api.addAdmin(obj.value);//提交新增数据
  search();//刷新表格
  addWinVisible.value = false;//关闭新增对话框

  // 发送全局事件通知其他组件刷新数据
  window.dispatchEvent(new CustomEvent('user-info-updated'));
}

const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
  console.log(index, row)
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await api.deleteAdmin(row.id);
        //重新加载数据
        //设置从第一页开始查询
        searchObj.value.current = 1;
        await search();

        // 发送全局事件通知其他组件刷新数据
        window.dispatchEvent(new CustomEvent('user-info-updated'));
      })
      .catch(() => {
      })
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  return dateTimeStr.replace('T', ' ');
}
</script>

<template>
  <!-- 模板部分保持不变 -->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
    <el-form-item label="用户名">
      <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable/>
    </el-form-item>
    <el-form-item label="手机号">
      <el-input v-model="searchObj.phone" placeholder="请输入手机号" clearable/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="resetSearch">重置</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handlerAdd">新增</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="id" label="管理员ID"></el-table-column>
    <el-table-column prop="username" label="管理员"></el-table-column>
<!--    <el-table-column prop="password" label="密码"></el-table-column>-->
    <el-table-column prop="email" label="邮箱"></el-table-column>
    <el-table-column prop="phone" label="手机号"></el-table-column>
    <el-table-column prop="avatar" label="头像">
      <template #default="scope">
        <el-image
            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]"
            style="width: 40px; height: 40px; object-fit: cover;"
            fit="cover"
            alt="用户头像"
        />
      </template>
    </el-table-column>
    <el-table-column prop="role" label="角色"></el-table-column>
    <el-table-column prop="create_time" label="注册时间">
      <template #default="scope">
        <span>{{ formatDateTime(scope.row.create_time) }}</span>
      </template>
    </el-table-column>
    <el-table-column label="处理按钮">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10,20,30,50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!--编辑对话框-->
  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="obj">
      <el-form-item label="用户名" :label-width="100">
        <el-input v-model="obj.username" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="密码" :label-width="100">
        <el-input v-model="obj.password" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="100">
        <el-input v-model="obj.email" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="手机号" :label-width="100">
        <el-input v-model="obj.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="头像" :label-width="100">
        <el-upload
            class="avatar-uploader"
            action="/api/user/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img v-if="obj.avatar" :src="obj.avatar" style="width:100px"/>
          <img v-else src='@/assets/upload.png' style="width:100px"/>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--新增对话框-->
  <el-dialog v-model="addWinVisible" title="新增" width="500">
    <el-form :model="obj">
      <el-form-item label="用户名" :label-width="100">
        <el-input v-model="obj.username" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="密码" :label-width="100">
        <el-input v-model="obj.password" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="100">
        <el-input v-model="obj.email" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="手机号" :label-width="100">
        <el-input v-model="obj.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="头像" :label-width="100">
        <el-upload
            class="avatar-uploader"
            action="/api/user/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img v-if="obj.avatar" :src="obj.avatar" style="width:100px"/>
          <img v-else src='@/assets/upload.png' style="width:100px"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="角色" :label-width="100">
        <el-input v-model="obj.role" value="管理员" disabled></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
